package com.universityJob.modules.sys.controller;

/**
 * @author mao on 2021/5/24.
 * @version 1.0 maozhijob@163.com
 */

import com.universityJob.common.utils.ExportExcel;
import com.universityJob.common.utils.FileUtil;
import com.universityJob.common.utils.R;
import com.universityJob.modules.sys.service.SysDataSourceService;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 系统日志
 *
 * @author Mark
 */
@RestController
@RequestMapping("/sys/dataSource")
public class SysDataSourceController {
    /**
     * 存储请求产生的文件名
     */
    Map<String, String> fileInfo = new HashMap<>();
    @Autowired
    private SysDataSourceService sysDataSourceService;
    private Logger logger = LoggerFactory.getLogger(getClass());
    /**
     * 备份、恢复文件路径
     */
    @Value("${upload.file}sql/")
    private String path;
    /**
     * 备份数据库
     * @return
     */
    @GetMapping("/backup")
    public R BackupDataSource() throws IOException {
        //向前端返回的数据
        Map<String, Object> data = new HashMap<>();

        String uid = UUID.randomUUID().toString().replaceAll("-", "");
        this.fileInfo.put(uid, "0");
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String format = simpleDateFormat.format(date);
        data.put("uid", uid);
        data.put("fileName", format+"数据库数据备份.sql");
        Thread thread = new Thread(() -> {
            try {
                int i = sysDataSourceService.BackupDataSource(path+"/"+format+"数据库数据备份.sql");
                this.fileInfo.put(uid, String.valueOf(i));
                logger.info("文件已经准备好，准备开始下载！");
            } catch (Exception e) {
                logger.error("文件导出出错！");
            }
        });
        thread.start();
        return R.ok(data);
    }

    /**
     * 恢复数据库
     * @return
     */
    @PostMapping("/recover")
    public R RecoverDataSource(@RequestParam("templateFile") MultipartFile file) throws IOException {
        //向前端返回的数据
        Map<String, Object> data = new HashMap<>();
        String uid = UUID.randomUUID().toString().replaceAll("-", "");
        data.put("uid", uid);
        data.put("fileName", "数据恢复");
        InputStream inputStream;
        try {
            inputStream = file.getInputStream();
            String name = file.getOriginalFilename();
            File tmpFile = File.createTempFile(name, ".tmp");
            FileUtils.copyInputStreamToFile(inputStream, tmpFile);
            Thread thread = new Thread(() -> {
                try {
                    int i = sysDataSourceService.RecoverDataSource(tmpFile);
                    this.fileInfo.put(uid, String.valueOf(i));
                    logger.info("文件恢复成功！");
                    tmpFile.delete();
                } catch (Exception e) {
                    logger.error("文件恢复出错！");
                    tmpFile.delete();
                }
            });
            thread.start();
        } catch (IOException e) {
            logger.error("文件恢复出错！");
            e.printStackTrace();
        }

        return R.ok(data);
    }
    /**
     * 循环请求接口
     */
    @PostMapping("/testpolling")
    @ResponseBody
    public R testPolling(@RequestBody Map<String, Object> param) {
        String uid = ExportExcel.nvll(param.get("uid"));
        String fileName = ExportExcel.nvll(param.get("fileName"));
        Map<String, Object> pollingData = new HashMap<>();
        pollingData.put(uid, fileInfo.get(uid));
        pollingData.put("fileName", fileName);
        return R.ok(pollingData);
    }
    /**
     * 最后下载的接口
     */
    @RequestMapping("/testdownload")
    @ResponseBody
    public void testDownload(HttpServletResponse response, @RequestParam Map<String, Object> param) {
        String fileName = (String) param.get("fileName");
        String uid = ExportExcel.nvll(param.get("uid"));
        String uidFolder = path;
        try {
            InputStream bis = new BufferedInputStream(new FileInputStream(new File(uidFolder + "/" + fileName)));
            fileName = URLEncoder.encode(fileName, "UTF-8");
            // 设置文件下载头
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            // 1.设置文件ContentType类型，这样设置，会自动判断下载文件类型
            response.setContentType("multipart/form-data;charset=utf-8");
            BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
            int len = 0;
            byte[] buf = new byte[2048];
            while ((len = bis.read(buf)) != -1) {
                out.write(buf, 0, len);
            }
            bis.close();
            out.close();
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //删除临时文件和文件信息
            FileUtil.deleteDirectory(uidFolder);
            fileInfo.remove(uid);
        }
    }
}
